#import "MYShopCouponView.h"

#import "MYShopSalesOrderVC.h"
#import "MYShopGoodsInsuranceTestifyVC.h"
#import "YQAddressManageVC.h"
#import "YQPCartListModel.h"
#import "YQPAddressModel.h"
#import "MYShopSettlementModel.h"
#import <AlipaySDK/AlipaySDK.h>
#import <WXApi.h>
#define KDEDUCTIONBTN_TAGBASE 11000
@interface MYShopSalesOrderVC ()
@property (nonatomic,retain) NSMutableDictionary *payParameters;
@property (nonatomic,retain) NSTimer *timer;

@property (strong, nonatomic) YQPCouponModel *couponModel;
@end

@implementation MYShopSalesOrderVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = kYQLS(@"确认订单");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySucceedAction) name:YJPaySucceedNotiKey object:nil];
}


-(void)subOrderAction:(UIButton *)sender {
    
    [MYShopSalesOrderPayView shopSalesOrderPayView:self.payTotal :^(NSInteger index, NSString * typeStr) {
        [self getOrderPayType:index];
    } :^{
        NSLog(@"");
    }];
}
///type 0支付宝 1微信 2.payply 3.线下支付
-(void)getOrderPayType:(NSInteger)type {
    NSMutableDictionary *par = [NSMutableDictionary dictionary];
    par[@"addressId"] = self.addresModel.addressId;

    par[@"isCoupon"] = self.settlementModel.isCoupon ? @"1":@"0";
    if (self.settlementModel.isCoupon) {//使用优惠券上传对应优惠券的id
        par[@"couponHistoryId"] = self.couponModel.couponHistoryId;
    }

    par[@"isIntegral"] = self.settlementModel.isIntegral ? @"1" : @"0";
    
    par[@"isFreightInsurance"] = self.settlementModel.isFreightInsurance ? @"1" : @"0";
    if (self.settlementModel.isFreightInsurance) {
        par[@"deliverMoney"] = [NSString stringWithFormat:@"%.2lf",self.settlementModel.deliverMoney];
    }
    par[@"postage"] = [NSString stringWithFormat:@"%@",self.postage];
    par[@"totalAmount"] = self.totalGoodsAmount;
    par[@"payAmount"] = self.payTotal;
    NSMutableArray *orderSkuList = @[].mutableCopy;
    for (YQPCartModel *cartModel in self.selectGoodArray) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"skuId"] = cartModel.skuId;
        dict[@"skuNumber"] = cartModel.itemNumber;
        dict[@"message"] = self.message;
        [orderSkuList addObject:dict];
    }
    
    par[@"orderSkuList"] = orderSkuList;
    
    YQSHOWLOADINGINVIEW
    [YQPNetWorkingManager sendPostRequest:kPOST_BASE_ORDER_SUBMIT_URL parameters:par    success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        YQHIDELOADINGTIPS
        if (responseObject.code == 0) {
            [self getPayDataOrderId:responseObject.data type:type];
        }else{
            YQUITIPSERROR(responseObject.msg)
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
        YQUITIPSERROR(error)
    }];
}

-(void)getPayDataOrderId:(NSString *)orderId type:(NSInteger)type {
    NSMutableDictionary *par = @{}.mutableCopy;
    par[@"orderId"] = orderId;
    par[@"payType"] = @(type + 1);
    par[@"orderType"] = @"1";
    self.payParameters=par;
    NSString *url=kALIPAY_ALIPAYPAYREQUEST_URL;
    if (type==1)//支付宝支付
    {
        url=kALIPAY_WECHATPAYPAYREQUEST_URL;
    }
   
        [YQPNetWorkingManager sendPostRequest:url parameters:par success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
            if (responseObject.code == 0) {
                if (type == 0) {
                    [self goToAlipayData:responseObject.data];
                }
                else
                {
                    NSDictionary *dict=(NSDictionary*)responseObject.data;
                    PayReq* req= [[PayReq alloc] init];
                    req.openID=[dict objectForKey:@"appId"];
                    req.partnerId= [dict objectForKey:@"partnerId"];
                    req.prepayId= [dict objectForKey:@"prepayId"];
                    req.nonceStr = [dict objectForKey:@"nonceStr"];
                    req.timeStamp= [[dict objectForKey:@"timestamp"] intValue];
                    req.package= [dict objectForKey:@"packageStr"];
                    req.sign= [dict objectForKey:@"sign"];
                    [WXApi sendReq:req completion:^(BOOL success) {
                        NSLog(@"1");
                    }];
                }
            }else{
                YQUITIPSERROR(responseObject.msg)
            }
        } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
            YQUITIPSERROR(error)
        }];
   
}

-(void)goToAlipayData:(NSString *)dataStr{
    NSString *appScheme = @"com.MuYing.www";
    [[AlipaySDK defaultService] payOrder:dataStr fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        //网页支付回调
        NSNotificationCenter *notiCenter=[NSNotificationCenter defaultCenter];
        //NSLog(@"result = %@",resultDic);
        NSString *resultStatus = resultDic[@"resultStatus"];
        if ([resultDic[@"memo"] isEqualToString:@""] && [resultStatus isEqualToString:@"9000"]) {
            /*支付成功通知*/
            [notiCenter postNotificationName:YJPaySucceedNotiKey object:self userInfo:nil];
        }else{
            
            if ([resultStatus isEqualToString:@"6001"]) {
                /*用户取消了支付*/
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    MBErrHUD(kYQLS(@"支付已取消"));
                });
            }else{
                NSString * strMsg = [NSString stringWithFormat:@"%@：%@,%@",kYQLS(@"支付结果"),kYQLS(@"支付失败"),resultDic[@"memo"]];
                NSLog(@"strMsg: %@",strMsg);
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
                [alert show];
            }
            
        }
    }];
}

-(void)paySucceedAction
{
   YQSHOWLOADINGINVIEW
   self.timer=[NSTimer scheduledTimerWithTimeInterval:2  target:self  selector:@selector(verifyPaymentResults) userInfo:nil  repeats:YES];
}

#pragma mark - 支付宝支付成功回调
- (void)verifyPaymentResults
{
    [YQPNetWorkingManager sendPostRequest:kPAYRETURN parameters:self.payParameters success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code == 0) {
            YQHIDELOADINGTIPS
            [self.timer invalidate];
            self.timer=nil;
            MYShopSalesOrderSucceedVC *succeedVC = [[MYShopSalesOrderSucceedVC alloc]initWithNibName:@"MYShopSalesOrderSucceedVC" bundle:nil];
            succeedVC.isIntegral = NO;
            succeedVC.navigationItem.title = kYQLS(@"支付成功");
            succeedVC.paySuceedLb.text = kYQLS(@"订单支付成功");
            succeedVC.paySuceedBtnText = kYQLS(@"查看我的订单");
            [self.navigationController pushViewController:succeedVC animated:true];
        }
        else if (responseObject.code==4) {
        }
        else
        {
                YQHIDELOADINGTIPS
                [self.timer invalidate];
                self.timer=nil;
                YQUITIPSERROR(responseObject.msg);
        }
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQHIDELOADINGTIPS
//        YQUITIPSERROR(error)
        [self.timer invalidate];
        self.timer=nil;
    }];
}


-(void)deductionAction:(UIButton *)sender {
//    sender.selected = !sender.selected;
    NSInteger tag = sender.tag - KDEDUCTIONBTN_TAGBASE;
    if (tag == 3) {
        //是否使用积分
        self.settlementModel.isIntegral = !self.settlementModel.isIntegral;
    }else{
        //是否使用优惠券
        self.couponModel.isSelect = !self.couponModel.isSelect;
    }
    self.bottonView.priceLb.text = [NSString stringWithFormat:@"%@: ￥%@",kYQLS(@"总计"),self.payTotal];
    [self.listTableView reloadData];
}
///是否购买运费险
-(void)freightInsurance:(UIButton *)sender {
    self.settlementModel.isFreightInsurance = !self.settlementModel.isFreightInsurance;
    self.bottonView.priceLb.text = [NSString stringWithFormat:@"%@: ￥%@",kYQLS(@"总计"),self.payTotal];
    [self.listTableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return [super tableView:tableView numberOfRowsInSection:section];
    }else if(section == 2) {
        return 4;
    }
    return 1;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return [super tableView:tableView cellForRowAtIndexPath:indexPath];
    }else if (indexPath.section == 1) {
        return [super tableView:tableView cellForRowAtIndexPath:indexPath];
    }else if (indexPath.section == 2) {
        if (indexPath.row == 0 || indexPath.row == 1) {
            MYShopSalesOrderRightLbCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYShopSalesOrderRightLbCell"];
            if (indexPath.row == 0) {
                cell.textLb.text = kYQLS(@"商品金额");
                cell.rightLb.textColor = kAPPThemeColor;
                cell.rightLb.text = [NSString stringWithFormat:@"￥%@",self.totalGoodsAmount];
            }else{
                cell.textLb.text = kYQLS(@"邮费");
                cell.rightLb.textColor = HexColor(0xA0A0A0);
                cell.rightLb.text = [NSString stringWithFormat:@"￥%@",self.postage];
            }
            return cell;
        }else{
            MYShopSalesOrderRightBtnCell *btnCell = [tableView dequeueReusableCellWithIdentifier:@"MYShopSalesOrderRightBtnCell"];
            btnCell.rightBtn.userInteractionEnabled = YES;
            if (indexPath.row == 2) {
                btnCell.textLb.text = kYQLS(@"优惠券");
                btnCell.rightBtn.selected = self.couponModel.isSelect;
                [btnCell.rightBtn setTitle:[NSString stringWithFormat:@"￥%.2lf",IsStrEmpty(self.couponModel.discountsAmount)?@(0.00).doubleValue:self.couponModel.discountsAmount.doubleValue] forState:(UIControlStateNormal)];
                [btnCell.rightBtn addTarget:self action:@selector(onShowCouponView) forControlEvents:UIControlEventTouchUpInside];
            }else{
                btnCell.textLb.text = kYQLS(@"积分抵扣");
                if (self.settlementModel.discountAmount > 0.0) {
                    btnCell.rightBtn.selected = self.settlementModel.isIntegral;
                    [btnCell.rightBtn setTitle:[NSString stringWithFormat:@"￥%.2lf",self.settlementModel.discountAmount] forState:(UIControlStateNormal)];
                    
                }else{
                    btnCell.rightBtn.userInteractionEnabled = NO;
                    btnCell.rightBtn.selected = self.settlementModel.isIntegral;
                    [btnCell.rightBtn setTitle:@"￥0.00" forState:(UIControlStateNormal)];
                }
            }
            btnCell.rightBtn.tag = KDEDUCTIONBTN_TAGBASE + indexPath.row;
            [btnCell.rightBtn addTarget:self action:@selector(deductionAction:) forControlEvents:(UIControlEventTouchUpInside)];
            return btnCell;
        }
    }
    MYShopSalesOrderInsuranceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MYShopSalesOrderInsuranceCell"];
    cell.textLb.text = kYQLS(@"购买运费险");
    [cell.rightBtn setTitle:[NSString stringWithFormat:@"￥%.2lf",self.settlementModel.deliverMoney] forState:(UIControlStateNormal)];
    ws(self);
    cell.rightBtn.selected = self.settlementModel.isFreightInsurance;
    [cell.rightBtn addTarget:self action:@selector(freightInsurance:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.detailsBtn addTapAction:^(id  _Nonnull sender) {
//        YQBaseWebVC *webVC = [[YQBaseWebVC alloc] init];
//        webVC.titleNav = @"投保须知";
//        webVC.urlStr = @"https://www.baidu.com";
//        [weakself.navigationController pushViewController:webVC animated:true];
    }];
    return cell;
}
#pragma mark - 优惠券弹框
- (void)onShowCouponView
{
    if (self.settlementModel.couponList.count == 0) {
        kMBMesHUD(@"暂无优惠券");
        return;
    }
    [MYShopCouponView showShopCouponViewWithModel:self.settlementModel resultBlack:^(YQPCouponModel * _Nonnull model) {
        if (!model) {
            kMBMesHUD(@"请选择优惠券");
            return;
        }else{//更新优惠券对应选中的信息
            self.couponModel = model;
            self.settlementModel.isCoupon = model.isSelect;
            self.bottonView.priceLb.text = [NSString stringWithFormat:@"%@: ￥%@",kYQLS(@"总计"),self.payTotal];
            [self.listTableView reloadData];
        }
    }];

}


@end
